package com.hd.trans.network.component

import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.hd.trans.network.HeaderInterceptor
import com.hd.trans.network.apiService.UrlConstant
import com.hd.trans.network.bean.UserInfoBean
import com.hd.trans.network.bean.aiChat.AIEventSSE
import com.hd.trans.network.bean.aiChat.AiChatError
import com.hd.trans.network.bean.aiChat.AiChatSseFrg
import com.hd.trans.network.bean.aiChat.AiChatTaskRequest
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.internal.sse.RealEventSource
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
import java.util.concurrent.TimeUnit

class AiChatSSEManager(handler: Handler?) {
    private var mHandler: Handler = handler ?: Handler(Looper.getMainLooper())

    private var realEventSource: RealEventSource? = null
    private val mGson: Gson by lazy {
        GsonBuilder().disableHtmlEscaping().create()
    }

    private val okHttpClient by lazy {
        //声明日志类
        //val httpLoggingInterceptor = HttpLoggingInterceptor()
        //httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        //不要添加作用于response的Interceptor，如日志打印，否则会阻塞SSE
        OkHttpClient.Builder()
            //.addInterceptor(httpLoggingInterceptor)
            .addInterceptor(HeaderInterceptor(false, true))
            .connectTimeout(30, TimeUnit.SECONDS) // 建立连接的超时时间
            .readTimeout(30, TimeUnit.MINUTES) // 建立连接后读取数据的超时时间
            .writeTimeout(30, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build()
    }

    fun cancel() {
        realEventSource?.cancel()
    }

    /**
     * @param input 输入内容
     * @param userinfoBean 用户信息
     * @param systemSetting 系统设置
     * @param history 历史记录
     * @param model AI模型, 默认:32k, 可选: 32k,128k,256k,deepseek,deepseekv3, 推荐使用deepseek, deepseekv3速度快没有深度思考
     * @param strict 文本检测严格模式,用于上架审核等情况，0：非严格模式，1：严格模式
     * @param limit 是否开启对用户的使用次数受后台预设限制. 0:关闭,1:开启, 默认:0
     * @param listener AiChatSSEListener
     */
    fun chatSSE(
        input: String,
        userinfoBean: UserInfoBean,
        systemSetting: String? = null,
        history: MutableList<String>? = null,
        model: String? = null,
        strict: Int = 0,
        limit: Int = 0,
        listener: AiChatSSEListener? = null
    ) {

        if(TextUtils.isEmpty(input)){
            listener?.onFailure(AiChatError(-1, "内容不能为空"))
            return
        }

        val body = AiChatTaskRequest(
            input,
            systemSetting,
            history,
            strict,
            limit,
            model ?: "deepseek"
        ).makeRequestBody(userinfoBean)

        makeRequest(body, listener)
    }

    private fun makeRequest(body: RequestBody, listener: AiChatSSEListener? = null) {

        val request: Request = Request.Builder()
            .url(UrlConstant.getV4ApiUrl() + "api/v4/sub/ai/doubao/chat/sse")
            .post(body)
            .build()

        realEventSource?.cancel()
        realEventSource = RealEventSource(request, object : EventSourceListener() {
            override fun onOpen(eventSource: EventSource, response: Response) {
                mHandler.post {
                    listener?.onStart()
                }
            }

            override fun onEvent(
                eventSource: EventSource,
                id: String?,
                type: String?,
                data: String
            ) {
                //Log.d("AiChatSSEManager", "data: ${data}, type: ${type}, id: $id")
                when (type) {
                    AIEventSSE.MESSAGE.value -> {
                        val answer: AiChatSseFrg = mGson.fromJson(data, AiChatSseFrg::class.java)
                        mHandler.post {
                            listener?.onEvent(answer)
                        }
                        if(answer.stop == 1 || answer.finish == 1){

                            mHandler.post {
                                listener?.onComplete()
                            }
                        }
                    }

                    AIEventSSE.ERROR.value -> {
                        val aiChatError: AiChatError = mGson.fromJson(data, AiChatError::class.java)
                        mHandler.post {
                            listener?.onFailure(aiChatError)
                        }
                    }
                }
            }

            override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
                if (response != null) {
                    val aiChatError = AiChatError(response.code, response.message)
                    mHandler.post {
                        listener?.onFailure(aiChatError)
                    }
                }
            }
        })
        realEventSource?.connect(okHttpClient)
    }
}
